package meta

import (
	"fmt"

	"github.com/micro-plat/hydra"
	"github.com/micro-plat/lib4go/errs"
)

func AddColumn(tenantID int, tableID int64, columnTitle, columnName, columnType string, isNullable, isDictLabel, isLikeQuery bool, source, method, param string, isPrefab bool, description string) (int64, error) {
	db, err := hydra.C.DB().GetRegularDB().Begin()
	if err != nil {
		return 0, err
	}

	// 判断字段名称是否重复
	exists, err := metaColumnExists(db, tenantID, tableID, columnName)
	if err != nil {
		db.Rollback()
		return 0, err
	}
	if exists {
		db.Rollback()
		return 0, errs.NewErrorf(500, "字段名称重复:%s", columnName)
	}

	// 添加字段数据到元数据表
	columnID, err := addMetaColumnByDB(db, tenantID, tableID,
		columnTitle, columnName, columnType, isNullable, isDictLabel, isLikeQuery, source, method, param, isPrefab, description)
	if err != nil {
		db.Rollback()
		return 0, err

	}

	// 获取数据表信息
	metaTable, err := getMetaColumnByColumnId(db, tenantID, columnID)
	if err != nil {
		db.Rollback()
		return 0, err
	}

	// 创建表结构
	err = apply(db, metaTable)
	if err != nil {
		db.Rollback()
		return 0, err
	}

	db.Commit()
	return columnID, nil
}

func UpdateColumn(tenantID int, columnID int64, columnTitle, columnName,
	columnType string, isNullable bool, isDictLabel, isLikeQuery bool, source, method, param string, isPrefab bool, description string) error {

	db, err := hydra.C.DB().GetRegularDB().Begin()
	if err != nil {
		return err
	}

	// 获取旧字段名称
	oldColumn, err := db.Scalar(sqlGetColumnName,
		map[string]interface{}{"tenant_id": tenantID, "column_id": columnID})
	if err != nil {
		db.Rollback()
		return err

	}

	err = updateMetaColumnByDB(db, tenantID, columnID, columnTitle, columnName, columnType,
		isNullable, isDictLabel, isLikeQuery, source, method, param, isPrefab, description)
	if err != nil {
		db.Rollback()
		return err

	}

	// 获取数据表信息
	metaTable, err := getMetaColumnByColumnId(db, tenantID, columnID, fmt.Sprint(oldColumn))
	if err != nil {
		db.Rollback()
		return err
	}

	// 创建表结构
	err = apply(db, metaTable)
	if err != nil {
		db.Rollback()
		return err
	}

	db.Commit()
	return nil

}
